<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cny extends Admin_Controller {
	private $dbconn;

	public function __construct(){  
		parent::__construct();
		$this->dbconn = $this->load->database('default',true);
	}

	//充值记录
	public function deposit(){
		$get		=	$this->input->get();
		$uid		=	isset($get['uid'])?$get['uid']:"";
		$orderno	=	isset($get['orderno'])?$get['orderno']:"";
		$where		=	"pay_status=1";
		$where		.=	!empty($uid)?" and uid ='$uid'":"";
		$where		.=	!empty($orderno)?" and orderno ='$orderno'":"";
		$nowpage	=	1;

		$this->load->library('pagination');//加载分页标签
		if(isset($get[$this->pagination->query_string_segment])){
			if(!empty($get[$this->pagination->query_string_segment])){
				$nowpage	=	$get[$this->pagination->query_string_segment];
			}
		}

		$this->load->config('cny');
		$bankArr= $this->config->item('bankArr');

		
		//加载分页数据model
		$this->load->model('Pagequery_model');
		$table			=	"cfd_cny_deposit";
		$order			=	"create_time DESC";
		$withdraw_log	=	$this->Pagequery_model->page_query($this->dbconn,$table,$order,$this->pagesize,$where,$nowpage);

		//加载文字处理类
		$this->load->library('ipoperation');
		if(!empty($withdraw_log))foreach($withdraw_log as &$items){
			$items['bank_name']	=	isset($bankArr[$items['bank_type']])?$bankArr[$items['bank_type']]:$items['bank_type'];
			$this->ipoperation->getIPArea($items['ip']);
			$country	=	$this->ipoperation->country;
			$province	=	$this->ipoperation->province;
			$city		=	$this->ipoperation->city;
			if(empty($country)&&empty($province)&&empty($city))$items['area']="-------";
			else $items['area']	=	$country." ".$province." ".$city;
		}

		$config['base_url']	  =	$this->get_url(array($this->pagination->query_string_segment));
		$config['total_rows'] = !empty($withdraw_log)?$withdraw_log[0]['Total']:0;
		$config['per_page']   = $this->pagesize;
		$config['do_jump']    = true;
		$config['use_page_numbers']=true;
		$this->pagination->initialize($config); 
		$this->data['page_html']	=	$this->pagination->create_links();
		$this->data['page']			=	'cny/deposit';
		$this->data['page_data']	=	$withdraw_log;
		$this->data['url']			=	$this->get_url(array('order','field',$this->pagination->query_string_segment));
		$this->data['get']			=	$get;
		$this->load->view('layout',$this->data);
	}

	//提现记录
	public function withdraw(){
		$get		=	$this->input->get();
		$uid		=	isset($get['uid'])?$get['uid']:"";
		$orderno	=	isset($get['orderno'])?$get['orderno']:"";
		$where		=	"1=1";
		$where		.=	!empty($uid)?" and uid ='$uid'":"";
		$where		.=	!empty($orderno)?" and orderno ='$orderno'":"";
		$nowpage	=	1;

		$this->load->library('pagination');//加载分页标签
		if(isset($get[$this->pagination->query_string_segment])){
			if(!empty($get[$this->pagination->query_string_segment])){
				$nowpage	=	$get[$this->pagination->query_string_segment];
			}
		}

		$this->load->config('cny');
		$bankArr= $this->config->item('bankArr');

		$this->load->model('cny_model');
		$bankLog	=	$this->cny_model->getCnyBank(array('1'=>1));
		$bankList	=	array();
		if(!empty($bankLog))foreach($bankLog as $bank){
			$bank['bank']			=	$bankArr[$bank['bank']];
			$bankList[$bank['id']]	=	$bank;
		}
		
		//加载分页数据model
		$this->load->model('Pagequery_model');
		$table			=	"cfd_cny_withdraw";
		$order			=	"create_time DESC";
		$withdraw_log	=	$this->Pagequery_model->page_query($this->dbconn,$table,$order,$this->pagesize,$where,$nowpage);

		//加载文字处理类
		$this->load->library('ipoperation');
		if(!empty($withdraw_log))foreach($withdraw_log as &$items){
			$items['bank']	=	$bankList[$items['bank_id']];	
			$this->ipoperation->getIPArea($items['ip']);
			$country	=	$this->ipoperation->country;
			$province	=	$this->ipoperation->province;
			$city		=	$this->ipoperation->city;
			if(empty($country)&&empty($province)&&empty($city))$items['area']="-------";
			else $items['area']	=	$country." ".$province." ".$city;
		}

		$config['base_url']	  =	$this->get_url(array($this->pagination->query_string_segment));
		$config['total_rows'] = !empty($withdraw_log)?$withdraw_log[0]['Total']:0;
		$config['per_page']   = $this->pagesize;
		$config['do_jump']    = true;
		$config['use_page_numbers']=true;
		$this->pagination->initialize($config); 
		$this->data['page_html']	=	$this->pagination->create_links();
		$this->data['page']			=	'cny/withdraw';
		$this->data['page_data']	=	$withdraw_log;
		$this->data['url']			=	$this->get_url(array('order','field',$this->pagination->query_string_segment));
		$this->data['get']			=	$get;
		$this->load->view('layout',$this->data);
	}

	//修改提现状态
	public function doWithdraw(){
		$get	=	$this->input->get();
		$sid	=	isset($get['sid'])?$get['sid']:0;
		$status	=	isset($get['status'])?$get['status']:0;
		$orderno=	isset($get['orderno'])?$get['orderno']:0;

		if(!in_array($status,array(1,-1))){
			$this->alertMsg("无效操作！");
		}
		
		$this->load->model('cny_model');
		$where_data	=	array('orderno'=>$orderno,'send_status'=>0);
		$order_info	=	$this->cny_model->getCnyWithdraw($where_data,1);
		if(empty($order_info)){
			$this->alertMsg("订单不存在！");
		}

		$uid	=	$order_info['uid'];
		$rs		=	false;
		try {
			$up_arr	=	array('send_status'=>$status,'send_time'=>date("Y-m-d H:i:s"));
			if(!$this->cny_model->updateWithdraw($up_arr,$where_data)){
				throw new Exception('L:'.__LINE__." 修改提现状态失败！", 1);
			}
			
			//取消订单返还人民币
			if($status == -1){
				$this->load->library('Cny_Class');
				$this->load->config('cny');
				$source = $this->config->item('back_withdraw_source');
				$add_arr  =  array(
					'uid'=> $uid,
					'name' => 'ACCOUNT',//帐户
					'use_value' => $order_info['amount'],
					'source' => $source,
					'add_time' => date("Y-m-d H:i:s"),
				);
				
				if(!$this->cny_class->add($add_arr)){
					throw new Exception('L:'.__LINE__." 取消订单返还人民币失败！", 1);
				}
				$this->cny_class->flushUserCache($uid);
			}
			$rs	=	true;
		} catch (Exception $e) {
			$rs	=	false;
		}


		if($rs){
			$data_arr	=	array(
				'admin_name'	=>	$this->admin_info['admin_name'],
				'admin_id'		=>	$this->admin_info['admin_id'],
				'action_time'	=>	date('Y-m-d H:i:s'),
				'action_memo'	=>	$status ==1?$orderno."：改为已发送":$orderno."：取消提现",
				'remark'		=>	'withdraw',
				'uid'			=>	$order_info['uid'],
				'last_time'		=>	date('Y-m-d H:i:s'),
				'status'		=>	1,
			);
			$this->load->library('Admin_Class');
			$this->admin_class->addOperationLog($data_arr);
			$this->alertMsg("操作成功！","/cny/withdraw?sid=".$sid);
		}else{
			$this->alertMsg("操作失败！","/cny/withdraw?sid=".$sid);
		}
	}

	//充值补发
	public function doDeposit(){
		$get	=	$this->input->get();
		$sid	=	isset($get['sid'])?$get['sid']:0;
		$orderno=	isset($get['orderno'])?$get['orderno']:0;


		$this->load->model('cny_model');
		$where_data	=	array('orderno'=>$orderno,'send_status'=>0);
		$order_info	=	$this->cny_model->getCnyDeposit($where_data,1);
		if(empty($order_info)){
			$this->alertMsg("订单不存在！");
		}

		$uid	=	$order_info['uid'];
		
		//补发人民币
		$this->load->driver('cache');
		$this->cache->redis->is_supported();
		$redis= $this->cache->redis->getClient();
		$rs	=	false;
		try {
			$redis->multi();
			$try  = 2; // 推两次都不行就不推了……
			do {
				$len = $redis->lPush('LIST_DEPOSIT', $orderno);
				if ($len != false) break;
				--$try;
			} while($try > 0);
			if ($len == false) throw new Exception('L:'.__LINE__.' 队列推送失败!', 1);
			$redis->exec();
			$rs	=	true;
		} catch (Exception $e) {
			$redis->discard();
			$rs	=	false;
			writeDebug('['.date("Y-m-d H:i:s").'] Err:'.$e->getMessage(),'ADMIN_CNY');
		}

		if($rs){
			$data_arr	=	array(
				'admin_name'	=>	$this->admin_info['admin_name'],
				'admin_id'		=>	$this->admin_info['admin_id'],
				'action_time'	=>	date('Y-m-d H:i:s'),
				'action_memo'	=>	"补发充值订单：".$orderno,
				'remark'		=>	'deposit',
				'uid'			=>	$order_info['uid'],
				'last_time'		=>	date('Y-m-d H:i:s'),
				'status'		=>	1,
			);
			$this->load->library('Admin_Class');
			$this->admin_class->addOperationLog($data_arr);
			$this->alertMsg("操作成功！","/cny/deposit?sid=".$sid);
		}else{
			$this->alertMsg("操作失败！","/cny/deposit?sid=".$sid);
		}
	}
}